import typing

from django.utils import timezone as dj_timezone

from apps.app_aai_proxy.models import AAIUserInfo


class UserInfoManager:
    UserType = AAIUserInfo.UserType

    @staticmethod
    def record_user(source_id: str, auth_type: str, true_name: str, email: str, org_name: str):
        """
        创建或者更新用户记录
        """
        if not true_name:
            true_name = ''

        if not org_name:
            org_name = ''

        now_dt = dj_timezone.now()
        user = AAIUserInfo.objects.filter(email=email).first()
        if user is not None:
            user.source_id = source_id
            user.type = auth_type
            if true_name:
                user.true_name = true_name

            if org_name:
                user.org_name = org_name

            user.update_time = now_dt
            user.save(update_fields=['source_id', 'type', 'true_name', 'org_name', 'update_time'])
            return user

        user = AAIUserInfo(
            source_id=source_id, email=email, type=auth_type, true_name=true_name, org_name=org_name,
            create_time=now_dt, update_time=now_dt
        )
        user.save(force_insert=True)
        return user

    @staticmethod
    def get_user_info(user_id: str) -> typing.Union[None, AAIUserInfo]:
        return AAIUserInfo.objects.filter(id=user_id).first()
